package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.repository.DestinationMongoRepository;
import cn.wolfcode.wolf2w.repository.StrategyThemeMongoRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    
    @Autowired
    private StrategyThemeMongoRepository strategyThemeMongoRepository;

    @Autowired
    private DestinationMongoRepository destinationMongoRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeMongoRepository.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeMongoRepository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeMongoRepository.deleteById(id);
    }

    @Override
    public StrategyTheme get(String id) {
        return strategyThemeMongoRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
        return strategyThemeMongoRepository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(QueryObject qo) {
        // 创建查询对象
        Query query = new Query();

        // 查询总条数
        long count = template.count(query, StrategyTheme.class);
        // 调用PageRequest 方法进行分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        // 给查询对象设置条件
        query.with(pageable);
        // 从mongodb 中查询符合条件的数据
        List<StrategyTheme> strategyThemes = template.find(query, StrategyTheme.class);
        // 返回当前页数据,分页和总长度
        return new PageImpl<>(strategyThemes , pageable , count);
    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if (StringUtils.hasLength(strategyTheme.getId())){
            this.update(strategyTheme);
        }else {
            this.save(strategyTheme);
        }
    }

}
